<?php

namespace application\Comm;

class Excel
{
    public $obj;

    public function init()
    {
        require(LIBRARY_PATH . '/Plug/Excel/PHPExcel.php');
        $this->obj = new \PHPExcel();
    }

    public function show($arr = [] ,$attribute =[])
    {

        $this->obj->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        ;
        $col = [
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        ];
        if (!empty($attribute)) {

            foreach ($arr as $k => $v) {
                $i = 0;
                foreach ($v as $key => $val) {
                    if(isset($col[$i])){
                        $index = $col[$i].'1';
                    }else{
                        $str = ($i+1)%26-1;
                        $index = $col[$str].'1';
                    }
                    $value = isset($attribute[$key])?$attribute[$key]:'';
                    $this->obj->setActiveSheetIndex(0)->setCellValue($index, $value);
                    $i++;
                }

            }
        }
        if (!empty($arr)) {
            $j=2;
            foreach ($arr as $k => $v) {
                $i = 0;
                foreach ($v as $key => $val) {
                    if(isset($col[$i])){
                        $index = $col[$i].$j;
                    }else{
                        $str = ($i+1)%26-1;
                        $index = $col[$str].$j;
                    }

                    $this->obj->setActiveSheetIndex(0)->setCellValue($index, $val);
                    $i++;
                }
                $j++;
            }
        }
        $title = '导出'.time();
        $this->obj->getActiveSheet()->setTitle($title);
    }

    public function save($name='export')
    {
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$name.date('Y-m-d').'.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($this->obj, 'Excel5');
        $objWriter->save('php://output');
    }

}
